package com.qf.service.impl;

import com.qf.dao.CommentMapper;
import com.qf.pojo.entity.QfComment;
import com.qf.pojo.repVo.BaseResp;
import com.qf.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    CommentMapper CommentMapper;
    @Autowired
    RedisTemplate redisTemplate;

    private static final String COMMENT_KEY="COMMENT_";

    //查询该课程的所有的评论
    @Override
    public BaseResp findCourseCommentByCourseId(Integer id, Integer page, Integer size) {

        Boolean aBoolean = redisTemplate.hasKey(COMMENT_KEY + id.toString());
        Integer start = (page-1)*size;
        List returnList=null;
        Long total=null;
        if (aBoolean){
            returnList=redisTemplate.opsForList().range(COMMENT_KEY+id.toString(),start,start+size-1);
            total=redisTemplate.opsForList().size(COMMENT_KEY+id.toString());
        }else{
            List<QfComment> byCourseId = CommentMapper.findByCourseId(id);
            if (byCourseId!=null&&byCourseId.size()>0){
                //放置到redis中
                redisTemplate.opsForList().rightPushAll(COMMENT_KEY + id.toString(),byCourseId);
                returnList=redisTemplate.opsForList().range(COMMENT_KEY+id.toString(),start,start+size-1);
                total=redisTemplate.opsForList().size(COMMENT_KEY+id.toString());
            }else {
                redisTemplate.opsForList().rightPush(COMMENT_KEY + id.toString(),"");
                redisTemplate.expire(COMMENT_KEY + id.toString(),10, TimeUnit.SECONDS);
            }
        }

        return new BaseResp(1,"查询成功！",returnList,total);
    }
}
